package com.qingfeng.base.secuity;

import com.qingfeng.base.model.TMenuResource;
import com.qingfeng.client.bean.Seller;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * url 验证权限
 * @Author:zhangyuefei
 * @Date:2019/9/6 16:51
 */
@Component("rbacService")
public class RbacService {
    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    /**
     * 判断url是否有权限
     * @param request
     * @param authentication
     * @return
     */
    public boolean hasPermission(HttpServletRequest request, Authentication authentication) {
        Object principal = authentication.getPrincipal();
        boolean hasPermission = false;
        if (principal instanceof Seller) { //首先判断先当前用户是否是我们UserDetails对象。
            Seller user = (Seller) principal;

            List<TMenuResource> resources = user.getResources();
            for (TMenuResource tMenuResource:resources){
                // 注意这里不能用equal来判断，因为有些URL是有参数的，所以要用AntPathMatcher来比较
                if (antPathMatcher.match(request.getContextPath()+tMenuResource.getPath(), request.getRequestURI())) {
                    hasPermission = true;
                    break;
                }
            }
        }else {
            throw new BadCredentialsException("未登录");
        }
//        return hasPermission;
        return true;
    }
}
